/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import com.sun.lwuit.Command;
import com.sun.lwuit.Form;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BorderLayout;
import core.DistrictsManager;
import core.DriverManager;
import core.ScreenEngine;
import datamodel.District;
import datamodel.DriverState;
import network.Connection;
import network.PacketBuilder;
import network.packets.MoveToDistrictResponce;
import network.packets.Packet;
import view.additional.CellItem;
import view.additional.ThumbList;
import view.additional.TickerRenderer;
import view.commands.BackCommand;

/**
 *
 * @author Kvest
 */
public class DistrictsForm extends Form implements DistrictsManager.ChangeNotifier
{
    private static final int MOVE_COMMAND_ID = 1;
    
    private ThumbList items;
    
    private Command move;
    
    public DistrictsForm()
    {
        super("districts");

        init();

        //Подписываемся на изменения районов
        DistrictsManager.getDistrictsManager().setChangeNotifier(this);
    }
    
    private void init()
    {
        setLayout(new BorderLayout());
        setScrollable(false);
        
        //Создаем список
        items = new ThumbList();
        items.setSelectCommandText("...");
        items.setFixedSelection(ThumbList.FIXED_NONE_CYCLIC);
        TickerRenderer render = new TickerRenderer();
        items.setRenderer(render);
        
        addComponent(BorderLayout.CENTER, items);
        
        //Команды
        move = new Command((DriverManager.getManager().getCurrenntState().getId() == DriverState.NOT_WORKING_STATE_ID ? "start_relay" : "move"), 
                            MOVE_COMMAND_ID)
        {
            public void actionPerformed(ActionEvent evt)
            {
                selectAction();
                
                evt.consume();
            }
        };
        addCommand(move);
        
        items.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent evt) 
            {
                move.actionPerformed(evt);
            }
        });
        
        addCommand(new BackCommand());
    }
    
    public void show()
    {
        move.setCommandName(DriverManager.getManager().getCurrenntState().getId() == DriverState.NOT_WORKING_STATE_ID ? "start_relay" : "move");

        //Обновляем контент
        updateContent();

        super.show();
    }
    
    private void updateContent()
    {
        synchronized(items)
        {
            //Удаляем все
            while(items.getModel().getSize() > 0)
            {
                items.getModel().removeItem(0);
            }

            DistrictsManager manager = DistrictsManager.getDistrictsManager();
            District district;
            for (int i = 0; i < manager.getDistrictsCount(); ++i)
            {
                district = manager.getDistrictByNumber(i);
                items.addItem(new CellItem(district.getId() , district.getFullDescription()));
            }
        }
    }
    
    private void selectAction()
    {
        CellItem selected = (CellItem)items.getSelectedItem();
        
        if (selected != null)
        {
            //Отображаем форму прогресса
            ScreenEngine.getEngine().push(new ProgressForm());
            
            //Регистрируем обработчик
            registerMoveToDistrictResponceListener();        
                    
            //Генерируем и отправляем запрос
            byte[] data = PacketBuilder.createMoveToDistrictRequest(DriverManager.getManager().getDriverID(), selected.getId()); 
            Connection.getConnection().send(data);
        }
    }
    
    private void registerMoveToDistrictResponceListener()
    { 
        Connection.getConnection().setPacketListener(Packet.MOVE_TODISTRICT_RESPONCE, new Connection.PacketNotifier() 
        {
            public void incomingPacket(Packet packet) 
            {
                MoveToDistrictResponce responce = (MoveToDistrictResponce)packet;
                
                //Сохраняем стоянку, где водитель реально зарегистрирован
                DriverManager.getManager().setDistrictID(responce.getDistrictID());
                
                if (responce.isResult())
                {
                     //Выталкиваем окна до самого первого(гл.меню)
                    ScreenEngine.getEngine().popTo(0);
                }
                else
                {
                    //Выталкиваем форму загрузки
                    ScreenEngine.getEngine().popProgressForm(true);
                    //ScreenEngine.getEngine().pop(true);
                    
                    //Отображаем сообщение с ошибкой
                    MessageBox.showModeless("error", "move_err");
                }
            }
        });
    }

    public void districtsChanged()
    {
        //ToDo Kvest
        //Тест запоминания выбранного элементв и возвращения к нему

        //Запомнить выбранный элемент
        CellItem selected = (CellItem)items.getSelectedItem();
        int currentSelectedID = -1;
        if (selected != null)
        {
            currentSelectedID = selected.getId();
        }
        
        updateContent();

        //Восстанавливаем выбранный элемент
        if (currentSelectedID != -1)
        {
            synchronized(items)
            {
                for (int i = 0; i < items.getModel().getSize(); ++i)
                {
                    if (((CellItem)items.getModel().getItemAt(i)).getId() == currentSelectedID)
                    {
                        items.setSelectedIndex(i);
                        break;
                    }
                }
            }
        }
    }
}
